<template>
  <div class="structure-detail">
    <div class="add-tab-btn">
      <el-button v-if="!tree.length" type="primary" size="mini" @click="handleisAddParent">添加组织</el-button>
      <el-button v-if="!tree.length" type="primary" size="mini" @click="handlePasteTheImport">粘贴导入</el-button>
    </div>

    <!-- 树 -->
    <div class="tree">
      <el-row style="margin-left: 0px; display: flex; justify-content: flex-end">
        <el-col>
          <el-input v-model="searchValue" placeholder="搜索组织" clearable size="mini" prefix-icon="el-icon-search"></el-input>
        </el-col>
      </el-row>

      <div style="margin-left: 0px; margin-right: 0px; padding-top: 20px">
        <el-row>
          <el-col :span="11">
            <div class="tree-container" style="width: 500px; height: 600px">
              <el-scrollbar style="height: 100%; width: 100%">
                <el-tree class="tree filter-tree organize-tree" ref="tree" :data="tree" :node-key="'key'" empty-text="" :indent="1" :props="defaultProps" highlight-current default-expand-all :expand-on-click-node="false" @node-click="handleNodeClick" :filter-node-method="handleFilterTree">
                  <div class="custom-tree-node" slot-scope="{ node, data }">
                    <el-tooltip class="item" effect="dark" :content="node.label" placement="top-start">
                      <span> {{ node.label | ellipsis(25) }} </span>
                    </el-tooltip>
                    <div class="operator">
                      <template v-if="data.parentKey === data.rootKey">
                        <el-button type="text" size="mini" @click.stop="() => handleAddChild(data)"> 添加 </el-button>
                        <el-button type="text" size="mini" v-if="strType != 1" @click.stop="() => handleClone(data)"> 克隆 </el-button>
                      </template>

                      <el-button type="text" size="mini" v-if="data.id !== 1" @click.stop="() => handleRemove(data)"> 删除 </el-button>
                    </div>
                  </div>
                </el-tree>
              </el-scrollbar>
            </div>
          </el-col>
          <el-col :span="11" style="margin-left: 70px">
            <!-- 新增组织 -->
            <div v-if="dialogFormVisible">
              <el-form :model="addForm" label-width="80px" :rules="nodeRules" ref="addForm" label-position="left" size="mini">
                <el-form-item label="组织名称" prop="orgName">
                  <el-input size="mini" v-model="addForm.orgName" maxlength="50" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="组织编码" prop="orgCode">
                  <el-input size="mini" v-model="addForm.orgCode" maxlength="50" disabled autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="组织类型" prop="orgType">
                  <el-select size="small" v-model="addForm.orgType">
                    <el-option v-for="(item, index) of nodeTypeList" :key="index" :label="item" :value="index" />
                  </el-select>
                </el-form-item>
                <!-- 组织类型为公司2\组织类型为部门5 6 8 -->
                <!-- <template v-if="addForm.orgType == 2 || addForm.orgType == 5 || addForm.orgType == 6 || addForm.orgType == 8">
                  <el-form-item label="关联项"
                                prop="sourceKey"
                                :rules="strType == 3 || strType == 2 ? [
                                  { required: true, message: '关联项不能为空'},
                                ] : [
                                  { required: false},
                                ]">
                    <el-select size="small" v-model="addForm.sourceKey" filterable clearable>
                        <el-option v-for="(item, index) in sourceList"
                                  :key="index"
                                  :label="item.orgName"
                                  :value="item.primaryKey"/>    
                    </el-select>
                  </el-form-item>
                </template> -->
                <el-form-item label="负责人" class="formhongxingdiandian" prop="manager" ref="managerForm">
                  <el-input :readonly="readonly" size="mini" v-model="addForm.managerName" autocomplete="off" @focus="inputHandle('manager')"></el-input>
                </el-form-item>
                <!--
                <el-form-item label="组织vp"
                              class="formhongxingdiandian"
                              prop="organizeLeader">
                  <el-input :readonly="readonly"
                            size="mini"
                            v-model="addForm.organizeLeaderName"
                            autocomplete="off"
                            @focus="inputHandle('leader')"></el-input>
                </el-form-item> -->

                <el-form-item label="组织介绍" prop="description">
                  <el-input size="mini" maxlength="140" type="textarea" v-model="addForm.description" placeholder="请输入组织介绍" show-word-limit :autosize="{ minRows: 4 }" resize="none"></el-input>
                </el-form-item>
                <el-form-item class="btn_all">
                  <el-button type="primary" size="small" @click="dialogFormVisible = false">取 消</el-button>
                  <el-button type="primary" size="small" @click="handleAddNode">确 定</el-button>
                </el-form-item>
              </el-form>
            </div>
            <!-- 组织反显 -->
            <div v-if="selectEditNode" style="margin: 0 10px 20px 10px">
              <el-form :model="selectedOrganize" label-width="80px" :rules="invertRules" ref="selectedOrganize" label-position="left" size="mini">
                <el-form-item label="组织名称" prop="orgName">
                  <el-input size="mini" maxlength="50" v-model="selectedOrganize.orgName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="组织编码" prop="orgCode">
                  <el-input size="mini" maxlength="50" v-model="selectedOrganize.orgCode" disabled autocomplete="off"></el-input>
                </el-form-item>
                <template v-if="selectedOrganize.rootPrimaryKey !== selectedOrganize.parentPrimaryKey">
                  <el-form-item label="组织类型" prop="orgType">
                    <el-select size="small" v-model="selectedOrganize.orgType">
                      <el-option v-for="(item, index) of nodeTypeList" :key="index" :label="item" :value="index" />
                    </el-select>
                  </el-form-item>
                </template>
                <!-- 组织类型为公司2\组织类型为部门5 6 8 -->
                <!-- <template v-if="selectedOrganize.orgType == 2 || selectedOrganize.orgType == 5 || selectedOrganize.orgType == 6 || selectedOrganize.orgType == 8">
                  <el-form-item label="关联项"
                                prop="sourceKey"
                                v-if="selectedOrganize.orgType == 2 || selectedOrganize.orgType == 5 || selectedOrganize.orgType == 6 || selectedOrganize.orgType == 8"
                                :rules="strType == 3 || strType == 2 ? [
                                  { required: true, message: '关联项不能为空'},
                                ] : [
                                  { required: false},
                                ]">
                    <el-select size="small" filterable clearable v-model="selectedOrganize.sourceKey">
                        <el-option v-for="(item, index) in sourceList"
                                  :key="index"
                                  :label="item.orgName"
                                  :value="item.primaryKey"/>
                    </el-select>
                  </el-form-item>
                </template> -->
                <el-form-item label="负责人" prop="managerName">
                  <el-input size="mini" v-model="selectedOrganize.managerName" autocomplete="off" @focus="inputHandle('manager')"></el-input>
                </el-form-item>
                <!-- 
                <el-form-item label="组织vp"
                              prop="organizeLeaderName">
                  <el-input size="mini"
                            v-model="selectedOrganize.organizeLeaderName"
                            autocomplete="off"
                            @focus="inputHandle('leader')"></el-input>
                </el-form-item> -->
                <el-form-item label="组织介绍" prop="description">
                  <el-input size="mini" maxlength="140" type="textarea" v-model="selectedOrganize.description" placeholder="请输入组织介绍" show-word-limit :autosize="{ minRows: 4 }" resize="none"></el-input>
                </el-form-item>
                <el-col :span="3" :offset="21" class="btn_all" style="margin-bottom: 20px">
                  <el-button type="primary" size="small" @click="selectEditNode = false">取 消</el-button>
                  <el-button type="primary" size="small" @click="ChangeSelectNode">保 存</el-button>
                </el-col>
              </el-form>
              <el-col v-if="selectedOrganize.rootPrimaryKey != selectedOrganize.parentPrimaryKey">
                <el-table :border="true" class="m-t-s" :data="structureTabDate" @selection-change="handleSelectionDel" size="mini">
                  <el-table-column align="center" type="selection"> </el-table-column>
                  <el-table-column label="序号" align="center">
                    <template slot-scope="scope"> {{ scope.row.sortNum }}<el-button style="margin-left: 10px" type="text" icon="el-icon-edit" @click="editSortNum(scope.row)" /> </template>
                  </el-table-column>
                  <el-table-column label="姓名" align="center" prop="employeeName" />

                  <el-table-column label="手机号" align="center" prop="employeeMobile" />
                  <el-table-column prop="date" label="操作" align="center">
                    <template slot-scope="scope">
                      <i class="btn-blue-color cursor-point" @click="changehandleClick(scope.row)">删除</i>
                    </template>
                  </el-table-column>
                </el-table>
                <el-col :span="4" :offset="20" class="btn_all" style="margin-top: 20px">
                  <el-button type="primary" size="small" @click="handleBatchDel">批量删除</el-button>
                  <el-button type="primary" size="small" @click="handleAddStructureStaff">新增人员</el-button>
                </el-col>
                <el-col class="t-right m-t-m">
                  <el-pagination v-if="totalAdd" style="margin-bottom: 30px" @current-change="pageChangeAdd" layout="prev, pager, next" :page-size="pageSizeAdd" :total="totalAdd"> </el-pagination>
                </el-col>
              </el-col>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 人员查找 -->
    <el-dialog title="负责人" :visible.sync="searchPeople" :close-on-click-modal="noCloseclickModal">
      <el-row class="search-principal-heard">
        <el-col :span="10" :offset="3" v-if="!switchView">
          <el-input class="search-input-text" v-model="inputAddPeople" placeholder="输入关键字进行过滤" clearable size="small">
            <template v-if="!switchView" #append>
              <el-button type="primary" size="small" icon="el-icon-search" @click="handleAddPeople">搜索</el-button>
            </template>
          </el-input>
        </el-col>

        <el-col :span="6" :offset="2" class="changeView">
          <!-- <el-button type="primary"
                     size="small"
                     @click="handleSwitchView">切换视图</el-button> -->
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8" v-if="switchView">
          <el-tree :data="changeTree" node-key="id" ref="tree" highlight-current default-expand-all :expand-on-click-node="false" :props="defaultProps" @node-click="handleCheckChange"></el-tree>
        </el-col>
        <el-col :span="!switchView ? 20 : 14">
          <el-table :data="searchTableData" border size="small" style="margin-left: 70px">
            <el-table-column label="姓名" align="center">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.employeeName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="手机号" align="center">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.mobile || scope.row.employeeMobile }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="handleChoseEdit(scope.row)">选为负责人</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-col>
            <el-pagination v-if="total" style="margin-left: 62px" :current-page.sync="currentPage" @current-change="pageChangeChoose" layout="prev, pager, next" :page-size="pageSize" :total="total"> </el-pagination>
          </el-col>
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 克隆 -->
    <el-dialog :title="isCloneMove" :visible.sync="isShowClone" :close-on-click-modal="noCloseclickModal">
      <el-row>
        <el-col :span="16">
          <el-select size="small" v-model="selectStructure" filterable placeholder="请选择" @change="selectCloneStructure">
            <el-option v-for="item in structureList" :key="item.primaryKey" :label="item.structureName" :value="item.primaryKey"> </el-option>
          </el-select>
        </el-col>
        <el-col :span="5" style="margin: 6px 0 0 10px">
          <el-checkbox v-model="checked">是否克隆当前人员</el-checkbox>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-tree style="width: 480px; height: 300px; overflow: auto" :data="SelectCloneTree" node-key="id" ref="cloneTree" default-expand-all :expand-on-click-node="false" highlight-current :props="defaultProps" @check-change="handleCloneChange">
            <div class="custom-tree-node" slot-scope="{ node, data }">
              <el-tooltip class="item" effect="dark" :content="node.label" placement="top-start">
                <span> {{ node.label | ellipsis(25) }} </span>
              </el-tooltip>
              <div class="operator">
                <el-button type="text" size="mini" @click.stop="() => handleSureClone(data)">
                  {{ isCloneMove == '克隆组织' ? '克隆当前组织' : '移动当前组织' }}
                </el-button>
              </div>
            </div>
          </el-tree>
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 新增人员 -->
    <el-dialog title="新增人员" :visible.sync="isAddStaff" :close-on-click-modal="noCloseclickModal">
      <el-row class="search-principal-heard">
        <el-col :span="15" :offset="2" v-if="!switchView">
          <el-input class="search-input-text" v-model="inputAddPeople" placeholder="输入关键字进行过滤" clearable size="small" @keyup.enter.native="handleAddPeople">
            <template v-if="!switchView" #append>
              <el-button type="primary" size="small" icon="el-icon-search" @click="handleAddPeople">搜索</el-button>
            </template>
          </el-input>
        </el-col>
        <!-- <el-col :span="5" :offset="2" v-if="!switchView">
          <el-button type="primary" size="small" @click="handleBatchAdd">批量添加</el-button>
        </el-col> -->
        <!-- <el-col :span="6" :offset="2" class="changeView m-b-s"> -->
        <!-- <el-button type="primary"
                     size="small"
                     @click="handleSwitchView">切换视图</el-button> -->
        <!-- </el-col> -->
      </el-row>
      <el-row>
        <el-col :span="8" v-if="switchView">
          <el-tree :data="changeTree" node-key="id" ref="tree" highlight-current default-expand-all :expand-on-click-node="false" :props="defaultProps" @node-click="handleCheckChange"></el-tree>
        </el-col>
        <el-col :offset="2" :span="!switchView ? 20 : 14">
          <el-table :data="addStaffTableData" style="" size="small" ref="addStaffTableData" border @selection-change="handleSelectionChange">
            <!-- <el-table-column type="selection"
                             width="55"
                             align="center">
            </el-table-column> -->
            <el-table-column label="姓名" align="center">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.employeeName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="手机号" align="center">
              <template slot-scope="scope">
                <span style="margin-left: 10px">{{ scope.row.mobile || scope.row.employeeMobile }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="text" @click="handleAddStaff(scope.row)">添加</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :offset="2" :span="20" class="m-t-s t-right">
          <el-pagination v-if="total" :current-page.sync="currentPage" @current-change="pageChange" layout="prev, pager, next" :page-size="pageSize" :total="total"> </el-pagination>
        </el-col>
      </el-row>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible" width="400px">
      <el-form ref="sortForm" size="small" label-position="left" :model="sortForm" :rules="sortRules" label-width="120px" @submit.native.prevent>
        <el-form-item label="人员顺序" prop="sortNum">
          <el-input placeholder="请输入人员顺序" type="number" v-model="sortForm.sortNum" clearable />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small" class="el-button-reset">取 消</el-button>
        <el-button type="primary" size="small" @click="saveBtn()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { organizeDelete, organizeTree, structureAddNode, structureNodeUpdate, structureNodeDelete, structureNodeDetail, structureCloneNode, structureMoveNode, structureStaffList, structureOrgStaffUpdate, addStaff, updateStaff, getHumanResourceTree, structureBatchCreate, employeeDelete, structurePatentImportCloneNode, nodeTreeExcel, nodeStructureSource, staffSearchList } from '../../../api/organization';
  import { structureList, structureUpdate, structureCreate, structureDetail, structureDelete, structureTree } from '../../../api/structure';
  import { dictionaryMap } from '../../../api/process';
  import structureTag from './StructureTag';
  export default {
    props: ['processData'],
    components: {
      structureTag,
    },
    watch: {
      searchValue(val) {
        this.$refs.tree.filter(val);
      },
      isCopy: {
        handler() {
          if (this.strType != 1 && this.tree.length) {
            return false;
          } else {
            return true;
          }
        },
        immediate: true,
      },
      'addForm.orgType'() {
        if (['2', '5', '6', '8'].includes(this.addForm.orgType)) {
          this.nodeStructureSource(this.addForm.orgType);
        }
      },
      'selectedOrganize.orgType'() {
        if (['2', '5', '6', '8'].includes(this.selectedOrganize.orgType)) {
          this.nodeStructureSource(this.selectedOrganize.orgType);
        }
      },
    },
    data() {
      const validatorManager = (rule, value, callback) => {
        if (!this.addForm.manager) {
          callback(new Error('请选择负责人'));
        } else {
          callback();
        }
      };

      const validatorLeader = (rule, value, callback) => {
        if (!this.addForm.organizeLeader) {
          callback(new Error('请选择组织vp'));
        } else {
          callback();
        }
      };
      return {
        nodeClickData: {},
        paginationShow: true,
        readonly: true,
        isAddTag: true,
        replaceFlag: false,
        isCopy: true,
        strType: 11,
        noCloseclickModal: false,
        checked: true,
        structureDescription: '',
        isPasteImport: false,
        total: 1,
        pageSize: 20,
        currentPage: 1,
        totalAdd: 1,
        pageSizeAdd: 10,
        currentPageAdd: 1,
        searchPeopleValue: '',
        addStaffTableData: [], // 人员添加表
        isAddStaff: false,
        isOrgUpdate: false,
        chooseManger: false,
        structuralLeaderUpdate: {}, // 组织负责人更新
        structureParams: {}, // 所选组织信息
        switchView: false, // 切换视图
        defaultSelect: '', // 默认选中
        structureTabDate: [],
        MoveNode: {},
        isCloneMove: '克隆组织',
        CloneNode: {},
        SelectCloneTree: [],
        selectStructure: '',
        structureList: [],
        isShowClone: false,
        structureItem: '',
        managerType: '0',
        personSelectInformation: {},
        selectEditNode: false,
        personInformation: {},
        searchTableData: [],
        inputSearchPeople: '',
        inputAddPeople: '',
        mineStatusValue: '',
        mineStatus: '',
        searchPeople: false,
        parentTreeNodeKey: '',
        rootPrimaryKey: '',
        addForm: {
          orgName: '',
          orgCode: '',
          orgType: '',
          sourceKey: '',
        },
        structureStatus: '',
        dictionary: '',
        form: {
          structureCode: '',
          structureName: '',
          structureType: '',
          organizeDesc: '',
          status: '',
        },
        dialogFormVisible: false,
        dialog: {
          create: {
            visible: false,
            node: {},
          },
        },
        searchValue: '',
        tree: [],
        changeTree: [],
        selectedOrganize: {},
        defaultProps: {
          children: 'children',
          label: 'name',
        },
        selectionTab: [],
        selectionTabDel: [],
        selectionTabCheckout: [],
        rules: {
          structureName: [{ required: true, message: '请输入结构名称', trigger: 'blur' }],
        },
        nodeRules: {
          orgName: [{ required: true, message: '请输入组织名称', trigger: 'blur' }],
          orgCode: [{ required: true, message: '请输入组织编码', trigger: 'blur' }],
          orgType: [{ required: true, message: '请选择组织类型', trigger: 'change' }],
          manager: [{ validator: validatorManager }],
          organizeLeader: [{ validator: validatorLeader }],
        },
        invertRules: {
          orgName: [{ required: true, message: '请输入组织名称', trigger: 'blur' }],
          orgCode: [{ required: true, message: '请输入组织编码', trigger: 'blur' }],
          orgType: [{ required: true, message: '请选择组织类型', trigger: 'change' }],
          managerName: [{ required: true, message: '请选择负责人', trigger: 'blur' }],
          organizeLeaderName: [{ required: true, message: '请选择组织vp', trigger: 'blur' }],
        },
        nodeTypeList: {
          9: '财务职能',
          10: '法务职能',
          11: '运营职能',
          12: '人力职能',
          13: 'IT职能',
          14: '行政职能',
          15: '其他职能',
        },
        sourceList: [], //所附属企业或人力组织
        selectPersonType: '',
        dialogVisible: false,
        personItem: {},
        sortForm: {
          sortNum: 1,
        },
        sortRules: {
          sortNum: [{ required: true, message: '请输入人员顺序', trigger: 'blur' }],
        },
        editSortNumPrimaryKey: '',
      };
    },
    mounted() {},
    methods: {
      //字典
      async getMap() {
        let res = await dictionaryMap();
        if (res) {
          this.nodeTypeList = res.orgType;
        }
      },
      getInfo() {
        // this.getMap()
        this.getStructureList();
        this.getStructureNodeTree();
        // this.getStructureNodeTree()
      },
      async nodeStructureSource(orgType) {
        let res = await nodeStructureSource(orgType);
        // this.addForm.sourceKey = ''
        // this.selectedOrganize.sourceKey = ''
        if (res.success != false) {
          this.sourceList = res || [];
        }
      },
      // 复选框控制disable
      checkboxT(row, index) {
        return row.handle == 'replace' ? 0 : 1;
      },
      //新增组织
      async handleisAddParent() {
        // this.selectEditNode = false
        // this.dialogFormVisible = true

        this.addForm.parentPrimaryKey = this.$route.query.strucCode;
        this.addForm.rootPrimaryKey = this.$route.query.strucCode;
        this.addForm.structureCode = this.$route.query.strucCode;
        this.addForm.treeNodeKey = '1234';
        this.addForm.orgName = '职能根组织';
        this.addForm.orgCode = new Date().getTime();
        this.addForm.orgType = -1;

        await structureAddNode(this.addForm);
        this.addForm = {};
        this.personSelectInformation = {};
        this.personSelectInformation;
        this.getStructureNodeTree();
      },
      // 批量删除
      async handleBatchDel() {
        let selectionTabDel = {};
        selectionTabDel.primaryKeys = [];
        this.selectionTabDel.forEach(item => {
          selectionTabDel.primaryKeys.push(item.primaryKey);
        });
        if (selectionTabDel.primaryKeys.length == 0) {
          this.$message.warning('请选择要删除的人员');
          return;
        }
        this.$confirm('此操作将永久删除人员, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            let res = await employeeDelete(selectionTabDel);
            if (res.success) {
              this.getStructureStaffListAdd();
              this.$message.success('删除成功!');
            } else {
              this.$message.error(res.message);
            }
          })
          .catch(() => {});
      },
      handleSelectionDel(val) {
        this.selectionTabDel = val;
      },
      // 批量添加
      async handleBatchAdd() {
        let selectionTab = {};
        selectionTab.employeePrimaryKeys = [];
        for (var i = 0; i < this.selectionTab.length; i++) {
          selectionTab.employeePrimaryKeys.push(this.selectionTab[i].employeePrimaryKey || this.selectionTab[i].primaryKey);
        }
        // 添加人员判断是否已经存在
        let flag = true;
        this.structureTabDate.forEach(item => {
          if (selectionTab.employeePrimaryKeys.indexOf(item.employeePrimaryKey) >= 0) {
            this.$message.warning('添加人员已存在');
            flag = false;
          }
        });
        selectionTab.organizationPrimaryKey = this.structureParams.organizationPrimaryKey;
        if (flag) {
          if (selectionTab.employeePrimaryKeys.length) {
            await structureBatchCreate(selectionTab);
            this.isAddStaff = false;
            this.$message.success('添加成功');
            this.selectionTabDel = [];
            this.getStructureStaffListAdd();
          } else {
            this.$message.warning('请选择要添加的人员');
          }
        }
      },
      // 多选框
      handleSelectionChange(val) {
        let selectChe = [];
        selectChe = val;
        this.selectionTab = selectChe;
      },
      // 新增人员方法
      async handleAddStaff(val) {
        // 添加人员判断是否已经存在
        let flag = true;
        this.structureTabDate.forEach(item => {
          if (item.employeePrimaryKey == val.primaryKey || item.employeePrimaryKey == val.employeePrimaryKey) {
            this.$message.warning('添加人员已存在');
            flag = false;
          }
        });
        if (flag) {
          this.isAddStaff = false;
          this.dialogVisible = true;
          this.personItem = val;
          this.sortForm.sortNum = 1;
          this.$nextTick(() => {
            this.$refs.sortForm.clearValidate();
          });
        }
      },
      editSortNum(item) {
        this.dialogVisible = true;
        this.editSortNumPrimaryKey = item.primaryKey;
        this.sortForm.sortNum = item.sortNum;
        this.personItem.primaryKey = item.employeePrimaryKey;
      },
      async saveBtn() {
        await this.$refs.sortForm.validate();
        let addstaffContent = {};
        addstaffContent.employeePrimaryKey = this.personItem.employeePrimaryKey || this.personItem.primaryKey;
        addstaffContent.organizationPrimaryKey = this.structureParams.organizationPrimaryKey;
        addstaffContent.sortNum = this.sortForm.sortNum;
        if (this.editSortNumPrimaryKey) {
          addstaffContent.primaryKey = this.editSortNumPrimaryKey;
        }
        this.editSortNumPrimaryKey ? await updateStaff(addstaffContent) : await addStaff(addstaffContent);
        this.$message.success('保存成功');
        this.dialogVisible = false;
        this.editSortNumPrimaryKey = '';
        this.getStructureStaffListAdd();
      },
      // 新增组织人员结构
      async handleAddStructureStaff() {
        this.isAddStaff = true;
        this.switchView = false;
        this.currentPage = 1;
        this.getstaffLich();
      },
      // 更新组织结构人员
      async structureOrgStaffUpdate() {
        let staffUpde = {};
        staffUpde.oldEmployeePrimaryKey = this.structuralLeaderUpdate.employeePrimaryKey;
        staffUpde.primaryKey = this.structuralLeaderUpdate.primaryKey;
        staffUpde.employeePrimaryKey = this.personSelectInformation.employeePrimaryKey || this.personSelectInformation.primaryKey;
        staffUpde.organizationPrimaryKey = this.structureParams.organizationPrimaryKey;
        if ((this.personSelectInformation.primaryKey == this.structuralLeaderUpdate.employeePrimaryKey || this.personSelectInformation.primaryKey == this.structuralLeaderUpdate.primaryKey) && this.replaceFlag) {
          this.$message.warning('不能重复替换当前负责人');
        } else {
          await structureOrgStaffUpdate(staffUpde);
          this.personSelectInformation.primaryKey = '';
          this.personSelectInformation.employeePrimaryKey = '';
          this.structuralLeaderUpdate = {};
          this.personSelectInformation = {};
          this.replaceFlag = false;
          this.chooseManger = false;
        }
      },
      // 替换结构上负责人
      async changehandleClick(val) {
        let staffDel = {};
        staffDel.primaryKey = val.primaryKey;
        this.$confirm('此操作将永久删除该负责人, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            let res = await employeeDelete(staffDel);
            if (res.success) {
              this.getStructureStaffListAdd();
              this.$message.success('删除成功!');
            } else {
              this.$message.error(res.message);
            }
          })
          .catch(() => {});
      },
      // 删除结构上人员
      async handleDelStaff(val) {
        let staffDel = val.primaryKey;
        await this.$confirm('此操作将永久删除该负责人, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        if (val.handle == 'delete') {
          let { rows } = await StructureDelete(staffDel);
          this.$message('删除成功');
          this.getStructureStaffListAdd();
        } else {
          await this.$confirm('该人员为该负责人, 替换后才能删除?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          });
        }
      },
      // 切换视图
      async handleSwitchView() {
        this.switchView = !this.switchView;
        this.currentPage = 1;
        if (this.switchView) {
          this.getHumanResourceTree();
        } else {
          this.handleSearchPeople();
        }
      },
      // 人力资源树
      async getHumanResourceTree() {
        let treeList = await getHumanResourceTree();
        this.changeTree = treeList.tree;
      },
      // 结构员工列表
      // async getStructureStaffList(type) {
      //   // this.structureParams.primaryKey = this.personInformation.primaryKey;
      //   if (!type) {
      //     this.currentPage = 1;
      //   }
      //   this.structureParams.pageSize = this.pageSize;
      //   this.structureParams.currentPage = this.currentPage;
      //   let { rows, total } = await structureStaffList(this.structureParams);
      //   this.structureTabDate = rows;
      //   this.total = Number(total);
      // },
      // 结构员工列表
      async getStructureStaffListAdd(type) {
        // this.structureParams.primaryKey = this.personInformation.primaryKey;
        if (!type) {
          this.currentPageAdd = 1;
        }
        this.structureParams.pageSize = this.pageSizeAdd;
        this.structureParams.currentPage = this.currentPageAdd;
        let { rows, total } = await structureStaffList(this.structureParams);
        this.structureTabDate = rows;
        this.totalAdd = Number(total);
      },
      // 1分页
      pageChangeAdd(val) {
        this.currentPageAdd = val;
        this.getStructureStaffListAdd('more');
      },
      async handleSureClone(data) {
        this.CloneNode.objectKey = data.key;
        this.CloneNode.cloneStaff = this.checked;
        if (this.defaultFirst && this.isCloneMove === '克隆组织') {
          this.CloneNode.cloneType = '3';
          await structurePatentImportCloneNode(this.CloneNode);
        } else {
          this.CloneNode.cloneType = '2';
          if (this.isCloneMove === '克隆组织') {
            await structureCloneNode(this.CloneNode);
          } else if (this.isCloneMove == '移动组织') {
            await structureMoveNode(this.CloneNode);
          }
        }

        this.CloneNode = {};
        this.isShowClone = false;
        this.defaultFirst = false;
        this.getStructureNodeTree();
      },
      // 克隆
      handleCloneChange(val) {
        this.CloneNode.objectKey = val.key;
      },
      async selectCloneStructure(val) {
        let treeList = await structureTree({
          primaryKey: '',
          structureCode: val,
          // rootPrimaryKey: val
        });
        this.SelectCloneTree = treeList.tree;
      },
      // 默认获取当前结构树
      async getStructureList() {
        let { rows } = await structureList({
          structureType: 7,
        });
        this.structureList = rows || [];
        if (this.structureList.length) {
          this.structureList.forEach(item => {
            if (item.primaryKey == this.$route.query.strucCode) {
              this.selectStructure = this.$route.query.strucCode;
            }
          });
          if (this.selectStructure) {
            this.selectCloneStructure(this.selectStructure);
          }
        }
      },
      // 克隆及上 首次加载当前结构
      handleClone(data) {
        this.getStructureList();
        this.CloneNode.targetKey = data.key || this.$route.query.strucCode;
        this.isCloneMove = '克隆组织';
        this.isShowClone = true;
      },
      // 更新组织信息及负责人
      async ChangeSelectNode() {
        await this.$refs.selectedOrganize.validate();
        this.selectEditNode = false;
        this.isOrgUpdate = false;
        await structureNodeUpdate(this.selectedOrganize);
        this.getStructureNodeTree();
      },
      // 负责人选择
      async handleChoseEdit(val) {
        this.chooseManger = true;
        this.personSelectInformation = val;
        this.switchView = false;

        if (this.selectPersonType == 'manager') {
          if (this.managerType == '0') {
            this.addForm.manager = val.employeePrimaryKey || val.primaryKey;
            this.addForm.managerName = val.employeeName;
          } else {
            this.selectedOrganize.manager = val.employeePrimaryKey || val.primaryKey;
            this.selectedOrganize.managerName = val.employeeName;
          }
        } else {
          if (this.managerType == '0') {
            this.addForm.organizeLeader = val.employeePrimaryKey || val.primaryKey;
            this.addForm.organizeLeaderName = val.employeeName;
          } else {
            this.selectedOrganize.organizeLeader = val.employeePrimaryKey || val.primaryKey;
            this.selectedOrganize.organizeLeaderName = val.employeeName;
          }
        }

        if (this.replaceFlag) {
          this.structureOrgStaffUpdate();
          this.selectEditNode = false;
          // setTimeout(this.getStructureStaffListAdd, 1500);
        }
        this.searchPeople = false;
      },
      // 人员列表
      async getstaffLich(type) {
        if (!type) {
          this.currentPage = 1;
        }
        let orgKeys = [];
        for (var i = 0; i < this.mineStatusValue.length; i++) {
          orgKeys.push(this.mineStatusValue[i].key);
        }
        let searchPeople = {};
        searchPeople.employeeName = this.inputAddPeople;
        searchPeople.orgKeys = orgKeys;
        searchPeople.pageSize = this.pageSize;
        searchPeople.currentPage = this.currentPage;
        searchPeople.workStatus = 1;
        let { rows, total } = await staffSearchList(searchPeople);
        this.addStaffTableData = rows;
        this.searchTableData = rows;
        this.total = Number(total);
        this.$nextTick(() => {
          this.addStaffTableData.forEach(row => {
            if (this.selectionTabCheckout.indexOf(row.primaryKey) >= 0) {
              this.$refs.addStaffTableData.toggleRowSelection(row, true);
            }
          });
        });
      },
      // 2人员分页
      pageChange(val) {
        this.currentPage = val;

        this.getstaffLich('more');
      },
      // input添加人员搜索2
      handleAddPeople() {
        this.getstaffLich();
      },
      // 分页选择3
      pageChangeChoose(val) {
        this.currentPage = val;

        this.getstaffLich('more');
      },
      // input搜人
      async handleSearchPeople() {
        let searchPeople = {};
        let orgKeys = [];
        for (var i = 0; i < this.mineStatusValue.length; i++) {
          orgKeys.push(this.mineStatusValue[i].key);
        }
        searchPeople.employeeName = this.inputSearchPeople;
        searchPeople.orgKeys = orgKeys;
        searchPeople.pageSize = this.pageSize;
        searchPeople.currentPage = this.currentPage;
        let { rows, total } = await staffSearchList(searchPeople);
        this.searchTableData = rows;
        this.total = total;
      },
      selectChange(e) {
        var arrNew = [];
        var dataLength = this.mineStatusValue.length;
        var eleng = e.length;
        for (let i = 0; i < dataLength; i++) {
          for (let j = 0; j < eleng; j++) {
            if (e[j] === this.mineStatusValue[i].name) {
              arrNew.push(this.mineStatusValue[i]);
            }
          }
        }
        this.$refs.tree.setCheckedNodes(arrNew); // 设置勾选的值
      },
      // 点击负责人组织获取人员
      async handleCheckChange(val) {
        let searchPeople = {};
        searchPeople.organizationPrimaryKey = val.key;
        searchPeople.pageSize = this.pageSize;
        searchPeople.currentPage = this.currentPage;
        let { rows, total } = await structureStaffList(searchPeople);
        this.searchTableData = rows;
        this.addStaffTableData = rows;
        this.total = Number(total);
        // let res = this.$refs.tree.getCheckedNodes(true, true); //这里两个true，1. 是否只是叶子组织 2. 是否包含半选组织（就是使得选择的时候不包含父组织）
        // let arrLabel = [];
        // let arr = [];
        // res.forEach(item => {
        //   arrLabel.push(item.name);
        //   arr.push(item);
        // });
        // this.mineStatusValue = arr;
        // this.mineStatus = arrLabel;
      },
      async inputHandle(type) {
        this.selectPersonType = type;
        this.inputAddPeople = '';
        this.searchPeople = true;
        this.currentPage = 1;
        this.switchView = false;
        this.handleSearchPeople();
      },

      async getStructureNodeTree() {
        let treeList = await structureTree({
          primaryKey: '',
          // rootPrimaryKey: this.$route.query.strucCode
          structureCode: this.$route.query.strucCode,
        });
        this.tree = treeList.tree || [];
      },
      async handleNodeClick(data) {
        this.$nextTick(() => {
          this.$refs.selectedOrganize.clearValidate();
        });

        this.nodeClickData = data;
        this.managerType = '1';
        this.dialogFormVisible = false;
        this.selectEditNode = true;
        this.isOrgUpdate = true;

        let res = await structureNodeDetail(data.key);
        this.selectedOrganize = res;
        this.selectedOrganize.orgType = String(this.selectedOrganize.orgType);
        // diao
        this.structureParams.currentPage = this.currentPage;
        this.structureParams.pageSize = this.pageSize;
        this.structureParams.organizationPrimaryKey = data.key;
        this.getStructureStaffListAdd();
      },

      handleFilterTree(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },

      async selectTree() {
        let data = await organizeTree(this.$store.state.enterpriseInfo.treeNodeKey || '');
        if (data.key) {
          this.tree = [data];
        }
      },

      handleAddChild(data) {
        this.addForm = {
          orgCode: new Date().getTime(),
        };

        this.managerType = '0';
        this.selectEditNode = false;
        this.dialogFormVisible = true;
        this.rootPrimaryKey = this.$route.query.strucCode;
        this.parentTreeNodeKey = data.key || this.$route.query.strucCode;
        this.personSelectInformation = {};
        this.isOrgUpdate = false;
        // this.dialog.create.node = data;
      },
      async cancelFieldValidate() {
        await this.$refs['managerForm'].clearValidate(); // 清除负责人验证
        // this.$nextTick(async () => {
        //   await this.$refs.addForm.clearValidate("manager");
        // });
      },

      async handleAddNode() {
        await this.$refs.addForm.validate();
        if (this.tree.length) {
          this.addForm.parentPrimaryKey = this.parentTreeNodeKey;
          this.addForm.rootPrimaryKey = this.rootPrimaryKey;
          this.addForm.structureCode = this.$route.query.strucCode;
          this.addForm.treeNodeKey = '1234';
        } else {
          this.addForm.parentPrimaryKey = this.$route.query.strucCode;
          this.addForm.rootPrimaryKey = this.$route.query.strucCode;
          this.addForm.structureCode = this.$route.query.strucCode;
          this.addForm.treeNodeKey = '1234';
        }
        await structureAddNode(this.addForm);
        this.addForm = {};
        this.personSelectInformation = {};
        this.personSelectInformation;
        this.dialogFormVisible = false;
        this.getStructureNodeTree();
      },
      /**
       *
       */
      async handleSave() {
        await this.$refs.organizeForm.handleSave();
        this.dialog.create.visible = false;
        this.selectTree();
      },

      /**
       * 删除树组织
       */
      handleRemove(data) {
        this.$confirm('此操作将永久删除该组织, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            let res = await structureNodeDelete(data.key);
            if (res.success) {
              this.$message.success('删除成功');
              this.getStructureNodeTree();
            } else {
              this.$message.error(res.message);
            }
          })
          .catch(() => {});
      },
      // 粘贴克隆
      handlePasteTheImport() {
        this.defaultFirst = true;
        this.CloneNode.targetKey = this.$route.query.strucCode;
        this.isCloneMove = '克隆组织';
        this.isShowClone = true;
        this.getStructureList();
      },
    },
  };
</script>
<style>
  .formhongxingdiandian .el-form-item__label::after {
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
  }
</style>
<style scoped lang="scss">
  .structure-detail {
    .save_sub {
      display: flex;
      justify-content: flex-end;
    }
    .structure-form {
      /* border-bottom: 1px solid #ccc; */
    }
    .tree-container ::v-deep .el-scrollbar .el-scrollbar__wrap {
      overflow-x: hidden;
    }
    /* 树形结构组织添加连线 */
    .tree ::v-deep .el-tree-node__content {
      padding-left: px;
    }
    .tree ::v-deep .el-tree-node {
      position: relative;
      padding-left: 8px;
    }

    .tree ::v-deep .el-tree-node__children {
      padding-left: 16px;
    }

    .tree ::v-deep .el-tree-node :last-child:before {
      height: 38px;
    }

    .tree ::v-deep .el-tree > .el-tree-node:before {
      border-left: none;
    }

    .tree-container ::v-deep .el-tree > .el-tree-node:after {
      border-top: none;
    }
    .el-tree > .el-tree-node {
      height: 350px;
      min-width: 100%;
      display: inline-block;
    }
    .tree ::v-deep .el-tree-node:before {
      content: '';
      left: -4px;
      position: absolute;
      right: auto;
      border-width: 1px;
    }

    .tree ::v-deep .el-tree-node:after {
      content: '';
      left: -4px;
      position: absolute;
      right: auto;
      border-width: 1px;
    }
    .tree ::v-deep .el-tree-node__expand-icon.is-leaf {
      display: none;
    }

    .tree ::v-deep .el-tree-node:before {
      border-left: 1px dashed #b8b9bb;
      bottom: 0px;
      height: 100%;
      top: -26px;
      width: 1px;
    }

    .tree ::v-deep .el-tree-node:after {
      border-top: 1px dashed #b8b9bb;
      height: 20px;
      top: 12px;
      width: 24px;
    }

    .left-col {
      /* border-right: #dcdfe6 solid 1px;
    margin-right: -1px; */
    }

    .right-col {
      border-left: #dcdfe6 solid 1px;
    }

    .el-tree-node__content {
      /*min-height: 26px;*/
      padding: 0px 0;
      height: unset;
    }

    .custom-tree-node {
      width: 80%;
      display: flex;
      align-items: center;
      justify-content: space-between;

      > .label {
        /*flex-grow: 1;*/
        width: calc(100% - 100px);
        white-space: pre-wrap;
        overflow: hidden;
        /*text-overflow: ellipsis;*/
      }

      > .operator {
        margin-left: 10px;
        flex-shrink: 0;
        width: 100px;
        text-align: right;
        position: absolute;
        right: 5px;
      }
    }
    .search-principal-heard {
      padding-bottom: 25px;
      .search-input-text {
      }
      .changeView {
        position: absolute;
        right: 0;
      }
      .addTable {
        margin-left: 109px;
      }
    }
  }
  .el-table td,
  .el-table th {
    text-align: center;
  }
  .btn_all {
    display: flex;
    justify-content: flex-end;
  }
  .el-select {
    display: block;
  }
</style>
